<template>
	<cl-crud :ref="setRefs('crud')" :on-refresh="onRefresh" @load="onLoad">
		<el-row type="flex" align="middle">
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn>批量删除</cl-multi-delete-btn>
			<cl-export-btn type="success" :columns="table.columns" />
			<cl-filter label="任课老师">
				<el-select
					size="mini"
					clearable
					v-model="form.class_teacher"
					@change="searchSubmit"
					style="width: 60px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in teachers_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<!-- <el-button type="success" size="mini" @click="getClassNum">发送请求</el-button> -->
			<!-- <cl-filter label="状态">
				<el-select size="mini" v-model="form.class_level">
					<el-option value="" label="全部"></el-option>
					<el-option :value="1" label="入门"></el-option>
					<el-option :value="2" label="初级"></el-option>
					<el-option :value="3" label="中级"></el-option>
					<el-option :value="4" label="高级"></el-option>
				</el-select>
			</cl-filter> -->
			<!-- <cl-filter label="课程类型">
				<el-select size="mini" v-model="form.status">
					<el-option v-for="item in class_type_list" :key='item.value' :value="item.value" :label="item.label"></el-option>
				</el-select>
			</cl-filter> -->

			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key />
		</el-row>
		<el-row>
			<cl-filter label="班号">
				<el-select
					size="mini"
					clearable
					v-model="form.class_number"
					@change="searchSubmit"
					style="width: 20px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in class_number_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="班级日期">
				<el-select
					size="mini"
					clearable
					v-model="form.class_date"
					@change="searchSubmit"
					style="width: 60px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in class_date_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="上课教室">
				<el-select
					size="mini"
					clearable
					v-model="form.class_class_classroom"
					@change="searchSubmit"
					style="width: 60px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in classroom_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="课程类型">
				<el-select
					size="mini"
					clearable
					v-model="form.class_course_type"
					@change="searchSubmit"
					style="width: 60px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in course_type"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="班级类型">
				<el-select
					size="mini"
					clearable
					v-model="form.class_type"
					@change="searchSubmit"
					style="width: 60px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in class_type_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="学生">
				<el-select
					size="mini"
					filterable
					clearable
					v-model="form.student_id"
					@change="searchSubmit"
					style="width: 120px"
				>
					<el-option :key="all" value="" label="全部"></el-option>
					<el-option
						v-for="item in students_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-flex1 />
			<el-button size="mini" type="success" @click="resetSerach">重置</el-button>
		</el-row>
		<el-row>
			<!-- 数据表格 -->
			<cl-table :ref="setRefs('table')" :show-summary="true" v-bind="table">
				<template #column-start_date="{ scope }">
					{{ scope.row.start_date.slice(0, 10) }}
				</template>
				<template #column-end_date="{ scope }">
					{{ scope.row.end_date.slice(0, 10) }}
				</template>
				<template #column-class_students="{ scope }">
					<el-tag
						v-for="(item, index) in scope.row.class_students_list"
						:key="index"
						disable-transitions
						size="small"
						effect="dark"
						style="margin: 2px"
						>{{ item }}</el-tag
					>
				</template>
				<template #column-date="{ scope }">
					<el-tag size="small" type="info">{{ scope.row.class_week+"：" + scope.row.class_start_time+"-"+ scope.row.class_end_time}}</el-tag>	
				</template>
			</cl-table>
		</el-row>

		<el-row type="flex">
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</el-row>

		<!-- 新增、编辑 -->
		<cl-upsert :ref="setRefs('upsert')" v-bind="upsert" @opened="onUpsertOpen">
			<template #slot-footer="{ scope }">
				<!-- <span class="dialog-footer"> -->
				<el-button
					size="mini"
					type="primary"
					v-show="saveAndCoutinue"
					@click="putInStorage(scope)"
					>保存并继续</el-button
				>
				<el-button size="mini" v-show="!saveAndCoutinue" type="primary" @click="editOrNew(scope)">复制新增</el-button>

				<!-- </span> -->
			</template>
		</cl-upsert>
	</cl-crud>
</template>

<script lang="ts">
import { defineComponent, inject, reactive, ref, onMounted } from "vue";
import { CrudLoad, Upsert, Table } from "cl-admin-crud-vue3/types";
import { useRefs } from "/@/core";
import axios from "axios";
import { baseUrl, URL } from "/@/config/env";
import { ElMessage } from "element-plus";
// import studentList from "../components/studentList.vue";
// import form from "element-plus/lib/components/form";

export default defineComponent({
	setup() {
		const { refs, setRefs } = useRefs();
		// 请求服务
		const service = inject<any>("service");

		// 定义班级列表
		const class_number_list = ref([]);

		// 保存登录用户的关联的教师id
		const teacherId = function () {
			const userInfo = JSON.parse(localStorage.getItem("userInfo")).teacher;
			console.log(userInfo);

			if (userInfo) {
				return userInfo.id;
			} else {
				return null;
			}
		};

		// 获取当前年份
		const getNowYear = function () {
			let date = new Date();
			date.getFullYear(); //获取完整的年份(4位)
			let season = "";
			if (date.getMonth() + 1 >=2  && date.getMonth() + 1 <= 7) {
				season = "春季";
			}else if ((date.getMonth() + 1 >=9  && date.getMonth() + 1 <= 12) || date.getMonth() + 1 === 1) {
				season = "秋季";
			}
			return date.getFullYear() + "年" + season;
		};

		const form = ref({
			class_number: "",
			class_date: getNowYear(),
			class_course_type: "",
			class_class_classroom: "",
			class_type: 1,
			class_teacher: teacherId(),
			student_id: ""
		});

		// 刷新监听
		async function onRefresh(params: any, { next, render }: any) {
			const { list } = await next(params);

			render(
				list.map((e: any) => {
					if (e.class_students) {
						e.class_students_list = e.class_students.split(",");
					}

					// e.status = Boolean(e.status);

					return e;
				})
			);
		}

		// 获取班级号
		const getClassNum = async function () {
			const res = await service.base.system.param.list({ keyName: "class_number" });

			let classNum = eval("(" + res[0].data + ")");
			classNum.forEach((item) => {
				class_number_list.value.push({
					value: "" + item.value,
					label: item.label
				});
			});
		};

		// 定义学生信息列表
		const students_list = ref([]);
		// 获取学生信息
		const getStudents = async function () {
			const res = await service.studentService.list();
			res.forEach((item, index) => {
				students_list.value.push({
					value: "" + item.id,
					label: item.name + " " + item.student_id
				});
			});
		};
		// 定义教师信息列表
		const teachers_list = ref([]);
		// 拼接教师信息请求路径
		// 获取教师信息
		const getTeacher = async function () {
			const res = await service.teacherService.list();
			const filteredItems = res.filter(item => item.is_work === 1);

			filteredItems.forEach((item, index) => {
				teachers_list.value.push({
					value: item.id,
					label: item.name
				});
			});
		};
		// 定义课程类型列表
		const course_type = ref([]);
		// 获取课程类型
		const getCourseType = async function () {
			const res = await service.courseTypeService.list();
			res.forEach((item, index) => {
				course_type.value.push({
					value: item.id,
					label: item.course_id,
					type: "warning"
				});
			});
		};

		// 定义上课教室列表
		const classroom_list = ref([]);
		// 获取课程类型
		const getClassroom = async function () {
			const res = await service.classroomService.list();
			res.forEach((item, index) => {
				classroom_list.value.push({
					value: "" + item.id,
					label: item.name,
					type: "danger"
				});
			});
		};

		// 定义班级类型
		const class_type_list = ref([]);
		// 获取班级号
		const getClassType = async function () {
			const res = await service.base.system.param.list({ keyName: "class_type" });
			let classType = eval("(" + res[0].data + ")");
			classType.forEach((item) => {
				class_type_list.value.push({
					value: parseInt(item.value),
					label: item.label,
					type: "success"
				});
			});
		};

		// 定义班级日期
		const class_date_list = ref([]);
		// 获取班级日期
		const getClassDate = async function () {
			const res = await service.base.system.param.list({ keyName: "class_date" });
			// 将json字符串转换为json对象
			let classDate = eval("(" + res[0].data + ")");
			classDate.forEach((item) => {
				class_date_list.value.push({
					value: "" + item.value,
					label: item.label,
					type: "info"
				});
			});
		};

		// 定义班级等级
		const class_level_list = ref([]);

		// 获取班级等级
		const getClassLevel = async function () {
			const res = await service.base.system.param.list({ keyName: "class_level" });
			// 将json字符串转换为json对象
			let classLevel = eval("(" + res[0].data + ")");
			classLevel.forEach((item) => {
				class_level_list.value.push({
					value: "" + item.value,
					label: item.label,
					type: "warning"
				});
			});
		};

		onMounted(async () => {
			// 获取所有教师信息
			getTeacher();
			// 获取所有学生信息
			getStudents();
			// 获取班级号
			getClassNum();
			// 获取课程类型
			getCourseType();
			// 获取班级类型
			getClassType();
			// 获取班级日期
			getClassDate();
			// 获取教室
			getClassroom();
			// 获取班级等级
			getClassLevel();
			searchSubmit();
		});

		// 新增、编辑配置
		const upsert = reactive<Upsert>({
			items: [
				{
					prop: "class_name",
					label: "班级名称",
					span: 12,
					component: {
						name: "el-input",
						props: {
							placeholder: "请输入班级名称"
						}
					},
					rules: {
						required: true,
						message: "班级名称不能为空"
					}
				},
				{
					prop: "class_course_type",
					label: "课程类型",
					span: 12,
					component: {
						name: "el-select",
						options: course_type.value,
						props: {
							placeholder: "请选择班级课程类型",
							filterable: true
						}
					},
					rules: {
						required: true,
						message: "班级课程类型不能为空"
					}
				},
				{
					prop: "class_date",
					label: "班级日期",
					span: 12,
					value: getNowYear(),
					component: {
						name: "el-select",
						options: class_date_list.value,
						props: {
							placeholder: "请选择班级日期"
						}
					},
					rules: {
						required: true,
						message: "班级日期不能为空"
					}
				},
				{
					prop: "class_type",
					label: "班级类型",
					span: 12,
					value: 1,
					component: {
						name: "el-select",
						options: class_type_list.value,
						props: {
							placeholder: "请输入班级类型"
						}
					},
					rules: {
						required: true,
						message: "班级类型不能为空"
					}
				},
				{
					prop: "start_date",
					label: "开学日期",
					span: 12,
					component: {
						name: "el-date-picker",
						props: {
							placeholder: "请输入开学日期"
						}
					},
					rules: {
						required: true,
						message: "开学日期不能为空"
					}
				},
				{
					prop: "end_date",
					label: "结课日期",
					span: 12,
					component: {
						name: "el-date-picker",
						props: {
							placeholder: "请输入结课日期"
						}
					},
					rules: {
						required: true,
						message: "结课日期不能为空"
					}
				},
				{
					prop: "class_number",
					label: "班级号",
					span: 12,
					component: {
						name: "el-select",
						options: class_number_list.value,
						props: {
							placeholder: "请输入班级号"
						}
					},
					rules: {
						required: true,
						message: "班级号不能为空"
					}
				},
				{
					prop: "class_teacher",
					label: "上课老师",
					span: 12,
					value: teacherId(),
					component: {
						name: "el-select",
						options: teachers_list.value,
						props: {
							placeholder: "请输入班级上课老师"
						}
					},
					rules: {
						required: true,
						message: "班级上课老师不能为空"
					}
				},
				{
					prop: "class_class_classroom",
					label: "上课教室",
					span: 12,
					component: {
						name: "el-select",
						options: classroom_list.value,
						props: {
							placeholder: "请选择班级上课教室"
						}
					},
					rules: {
						required: true,
						message: "班级上课教室不能为空"
					}
				},
				{
					prop: "class_level",
					label: "班级等级",
					span: 12,
					component: {
						name: "el-select",
						options: class_level_list.value,
						props: {
							placeholder: "请选择班级等级"
						}
					},
					rules: {
						required: true,
						message: "班级等级不能为空"
					}
				},
				{
					prop: "class_week",
					label: "上课星期",
					span: 12,
					component: {
						name: "el-select",
						options: [
							{
								label: "星期1",
								value: "星期1"
							},
							{
								label: "星期2",
								value: "星期2"
							},
							{
								label: "星期3",
								value: "星期3"
							},
							{
								label: "星期4",
								value: "星期4"
							},
							{
								label: "星期5",
								value: "星期5"
							},
							{
								label: "星期6",
								value: "星期6"
							},
							{
								label: "星期7",
								value: "星期7"
							}
						],
						props: {
							placeholder: "请选择班级上课星期"
						}
					},
					rules: {
						required: true,
						message: "班级上课星期不能为空"
					}
				},
				{
					prop: "class_start_time",
					label: "开始时间",
					span: 12,
					component: {
						name: "el-time-select",
						start: "08:30",
						step: "00:05",
						end: "19:30",
						props: {
							placeholder: "请输入上课开始时间"
						}
					},
					rules: {
						required: true,
						message: "上课开始时间不能为空"
					}
				},
				{
					prop: "class_end_time",
					label: "结束时间",
					span: 12,
					component: {
						name: "el-time-select",
						start: "08:30",
						step: "00:05",
						end: "19:30",
						props: {
							placeholder: "请输入上课结束时间"
						}
					},
					rules: {
						required: true,
						message: "上课结束时间不能为空"
					}
				},
				{
					prop: "class_students",
					label: "班级学生",
					hook: {
						bind: ["split", "number"] // 通道流程，分割 -> 转成number -> 绑定值
					},
					span: 12,
					// hook: {
					// 	bind: (value, form) => {
					// 	// value 是与 prop 绑定的值
					// 	// form 是表单值
					// 	console.log(value);

					// 	return value.split(",").map(Number).filter(Boolean); // 结果为：[1, 2, 3],  // 绑定通道流程，分割 -> 转成number -> 绑定值
					// 	}
					// },
					// value:16,
					// component: studentList,
					component: {
						name: "studentList",
						props: {
							placeholder: "请输入班级学生"
						}
						// multiple: true,
						// clearable: true,
						// filterable: true,
						// options: students_list.value
					},
					rules: {
						required: true,
						message: "班级学生不能为空"
					}
				},
				{
					prop: "note",
					label: "备注",
					span: 24,
					component: {
						name: "el-input",
						props: {
							placeholder: "请输入备注",
							type: "textarea"
						}
					},
					rules: {
						required: false,
						message: "备注可以为空"
					}
				}
				// {
				// 	prop: "class_date",
				// 	label: "班级日期",
				// 	span: 24,
				// 	value: 1,
				// 	component: {
				// 		name: "el-radio-group",
				// 		options: [
				// 			{
				// 				label: "男",
				// 				value: 1
				// 			},
				// 			{
				// 				label: "女",
				// 				value: 0
				// 			}
				// 		]
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "性别不能为空"
				// 	}
				// },
				// {
				// 	prop: "birthday",
				// 	label: "出生日期",
				// 	span: 24,
				// 	component: {
				// 		name: "el-date-picker",
				// 		props: {
				// 			placeholder: "请选择出生日期"
				// 		}
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "出生日期不能为空"
				// 	}
				// },
				// {
				// 	prop: "phone",
				// 	label: "手机号",
				// 	span: 24,
				// 	component: {
				// 		name: "el-input",
				// 		props: {
				// 			placeholder: "请输入手机号"
				// 		}
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "手机号不能为空"
				// 	}
				// },
				// {
				// 	prop: "status",
				// 	label: "状态",
				// 	span: 24,
				// 	value: 2,
				// 	component: {
				// 		name: "el-radio-group",
				// 		options: [
				// 			{
				// 				label: "停学",
				// 				value: 0
				// 			},
				// 			{
				// 				label: "停课",
				// 				value: 1
				// 			},
				// 			{
				// 				label: "在读",
				// 				value: 2
				// 			}
				// 		]
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "状态不能为空"
				// 	}
				// },
				// {
				// 	prop: "into_date",
				// 	label: "报名日期",
				// 	span: 24,
				// 	component: {
				// 		name: "el-date-picker",
				// 		props: {
				// 			placeholder: "请选择报名日期"
				// 		}
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "报名日期不能为空"
				// 	}
				// },
				// {
				// 	prop: "stop_time",
				// 	label: "暂停时间",
				// 	span: 24,
				// 	component: {
				// 		name: "el-date-picker",
				// 		props: {
				// 			placeholder: "请选择暂停时间"
				// 		}
				// 	}
				// },
				// {
				// 	prop: "note",
				// 	label: "备注",
				// 	span: 24,
				// 	component: {
				// 		name: "el-input",
				// 		type: "textarea",
				// 		size: "medium",
				// 		props: {
				// 			placeholder: "请输入备注"
				// 		}
				// 	}
				// }
			],
			op: {
				// hidden:false,
				// saveButtonText: "重置",
				// closeButtonText:'关闭1',
				buttons: ["slot-footer", "save", "close"]
			}
		});

		// 表格配置
		const table = reactive<Table>({
			columns: [
				{
					type: "selection",
					width: 60
				},
				{
					type: "index",
					label: "#",
					width: 60
				},
				{
					prop: "class_date",
					label: "班级日期",
					width: 120,
					dict: class_date_list.value
				},
				{
					prop: "class_name",
					label: "班级名称"
					// width: 120
				},
				{
					prop: "class_number",
					label: "班级号",
					width: 120,
					dict: class_number_list.value
				},
				{
					prop: "class_course_type",
					label: "班级课程类型",
					width: 140,
					dict: course_type.value
				},
				{
					prop: "class_type",
					label: "班级类型",
					width: 80,
					dict: class_type_list.value
				},
				{
					prop: "class_teacher",
					label: "班级任课老师",
					width: 95,
					dict: teachers_list.value
				},
				{
					prop: "class_class_classroom",
					label: "班级上课教室",
					width: 160,
					dict: classroom_list.value
				},
				// {
				// 	prop: "start_date",
				// 	label: "开课日期",
				// 	width: 100
				// },
				{
					prop: "date",
					label: "上课时间",
					width: 150
				},
				{
					prop: "class_students",
					label: "学生",
					width: 300,
					dict: students_list.value
				},
				{
					label: "操作",
					type: "op"
				}
			]
		});

		// crud 加载
		function onLoad({ ctx, app }: CrudLoad) {
			// 绑定 service
			ctx.service(service.classgroupService).done();
			app.refresh();
		}

		// 筛选按钮提交
		const searchSubmit = function () {
			console.log(form.value.class_number);
			refs.value.crud.refresh({ ...form.value });
		};
		// 重置筛选条件

		const resetSerach = function () {
			form.value = {
				class_number: "",
				class_date: "",
				class_course_type: "",
				class_class_classroom: "",
				class_type: "",
				class_teacher: "",
				student_id: ""
			};
			refs.value.crud.refresh({ ...form.value });
		};

		// 自定义新增/编辑对话框的操作按钮-再次入库
		const putInStorage = function (scope: any) {
			// 删除id避免提交时为更新操作
			delete refs.value.upsert.form.id;
			refs.value.upsert.validate(async (valid) => {
				if (valid) {
					const res = await service.classgroupService.add(refs.value.upsert.modelValue);
					if (!res) {
						ElMessage(`添加失败:${res}`);
					}

					ElMessage({
						message: "添加成功，请继续添加",
						type: "success"
					});
					// 修改成新增模式
					refs.value.upsert.isEdit = false;

					// 重置上课班级
					refs.value.upsert.form.teaching_class = null;

					// 重置班级等级
					refs.value.upsert.form.class_level = null;

					// 重置上课星期
					refs.value.upsert.form.class_week = null;
					// 重置上课开始时间
					refs.value.upsert.form.class_start_time = null;
					// 重置上课结束时间
					refs.value.upsert.form.class_end_time = null;
					// 重置班级学生
					refs.value.upsert.form.class_students = null;
					// 重置备注

					refs.value.upsert.form.note = null;

					// 设置标题为新增
					refs.value.upsert.setTitle("新增");
					refs.value.crud.refresh();
				} else {
					ElMessage({
						type: "error",
						message: "数据未填写完整！"
					});
					return false;
				}
			});
		};

		// 自定义编辑/新增对话框的操作按钮-再次便捷新增
		const editOrNew = function (scope: any) {
			// 删除id避免提交时为更新操作
			delete refs.value.upsert.form.id;
			// 修改成新增模式
			refs.value.upsert.isEdit = false;

			// 重置班级名称
			// refs.value.upsert.form.class_name = null;

			// 重置课程类型
			refs.value.upsert.form.class_course_type = null;

			// 重置班级日期
			refs.value.upsert.form.class_date = getNowYear();

			// 重置开学日期
			// refs.value.upsert.form.start_date = null;
			// 重置结课日期
			// refs.value.upsert.form.end_date = null;

			// 重置备注
			refs.value.upsert.form.note = null;

			// 设置标题为新增
			refs.value.upsert.setTitle("新增");
			// refs.value.upsert.validate(async (valid) => {
			// 	if (valid) {
			// 		const res = await service.classgroupService.add(refs.value.upsert.modelValue);
			// 		if (!res) {
			// 			ElMessage(`添加失败:${res}`);
			// 		}

			// 		ElMessage({
			// 			message: "添加成功，请继续添加",
			// 			type: "success"
			// 		});

			// 		refs.value.crud.refresh();
			// 	} else {
			// 		ElMessage({
			// 			type: "error",
			// 			message: "数据未填写完整！"
			// 		});
			// 		return false;
			// 	}
			// });
		};

		// 设置保存并继续的按钮是否显示
		const saveAndCoutinue = ref(false);

		// 打开新增、编辑对话框的钩子函数
		const onUpsertOpen = () => {
			if (!refs.value.upsert.isEdit) {
				saveAndCoutinue.value = true;
			} else {
				saveAndCoutinue.value = false;
			}
		};

		return {
			refs,
			setRefs,
			upsert,
			table,
			onLoad,
			getClassNum,
			onRefresh,
			students_list,
			class_type_list,
			form,
			searchSubmit,
			class_number_list,
			class_date_list,
			course_type,
			teachers_list,
			classroom_list,
			resetSerach,
			putInStorage,
			editOrNew,
			saveAndCoutinue,
			onUpsertOpen
		};
	}
});
</script>
